<template>
  <div class="page-container">
    <van-cell-group>
      <van-field
        ref="scanDom"
        v-model="scan"
        label=""
        label-width="130"
        left-icon="scan"
        style="background-color:lightYellow"
        placeholder="扫描配送单号"
        size="large"
        clearable
        border
        @keyup.enter.native="handleScanOver"
        @clear="handleScanClear"
        @click-left-icon="handleScanClear"
      />

      <van-field label="配送单号:" label-align="right" v-model="dist.busKey" size="mini" disabled />
      <van-field label="金额:" label-align="right" v-model="dist.amount" size="mini" disabled />
      <van-field label="科室:" label-align="right" v-model="dist.deptName"  size="mini" disabled />
      <van-field label="收货人:" label-align="right" ref="receiverDOM" v-model="dist.receiver"  size="mini" disabled/>
    </van-cell-group>
    <van-divider><span style="font-size:9px">配送单明细</span></van-divider>
    <div class="items-container">
      <van-collapse v-model="activeNames">
        <van-collapse-item
          v-for="distItem in distItems"
          :key="distItem.id"
          :name="distItem.id">
          <template #title>
            <div>
              <span class="matr-name">{{distItem.matrName}}</span>
            </div>
            <div>
              <span class="matr-spec">{{distItem.matrSpec}}</span>
            </div>
          </template>
          <template #value>
            <div class="value-container">
              <div><van-icon name="shopping-cart-o" /><label class="matr-qty">{{distItem.pickedSkuQty}}</label></div>
              <div>{{distItem.skuUnit}}</div>
            </div>
          </template>
          <template>
            <div>
              <receive-item propTitleMode />
              <receive-item
                v-for="pickItem in getPickItems(distItem)"
                :key="pickItem.id"
                :value="pickItem"
              />
            </div>
          </template>
        </van-collapse-item>
      </van-collapse>
    </div>
    <div class="btn-container" v-if="dist.id">
      <flow-buttons
        :propFlowKey="propFlowKey"
        plain
        @button-click="handleFlowButtonClick"
        style="width:100%" />
    </div>
  </div>
</template>

<script>
import FlowButtons from '@/components/FlowButtons'
import ReceiveItem from './ReceiveItem'


export default {
  data() {
    return {
      activeNames: [],
      scan: '',
      dist: {},
      distItems: [],
      pickItems: [],
      flowButton: {}
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
  },
  computed: {
    cpButtonDisable() {
      return !this.dist.id
    }
  },
  methods: {
    getFlowNodeValue() {
      if (this.propFlowKey) {
        return this.propFlowKey.split(':')[1]
      }
    },
    getPickItems(distItem) {
      return this.pickItems.filter(item => item.distItemId == distItem.id)
    },
    handleScanClear(event) {
      this.scan = ''
    },
    handleScanOver() {
      if (window.isPDAScan()) this.scan = window.getPDAScan()
      if (!this.scan) return
      this.handleReceiveDist(this.scan)
    },
    handleReceiveDist(distKey) {
      const params = { distKey }
      this.utils.loadShow()
      this.$ajax.get('/wm/dist/getDistByKey', { params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          if (response.data.dist.flowStatus != this.getFlowNodeValue()) {
            this.$notify.warning('该配送单未处于可配送状态')
            return
          }
          this.dist = response.data.dist
          this.distItems = response.data.distItems
          this.pickItems = response.data.pickItems
          this.resetScan()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    async handleFlowButtonClick(button) {
      this.flowButton = button
      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      })
      if (!result) return
      const flowKey = this.propFlowKey.split(':')[0]
      const params = {
        flowKey,
        buttonKey: this.flowButton.code,
        busId: this.dist.id
      }
      this.$ajax.post('/wm/dist/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.$notify.success(`${this.flowButton.title}操作成功！`)
          this.printDistQR()
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    getPrintData() {
      let skuQtySum = 0
      let distSummary = ''
      this.pickItems.forEach(pickItem => { skuQtySum += pickItem.skuQty })
      if (this.pickItems.length > 1) {
        const first = this.pickItems[0]
        distSummary = `${first.matrName} 等共 ${skuQtySum} 件`
      } else if (this.pickItems.length == 1) {
        const first = this.pickItems[0]
        distSummary = `${first.matrName} 共 ${skuQtySum} ${first.skuUnit}`
      }
      const dist = {
        busKey: this.dist.busKey,
        busKeyQR: this.dist.busKey,
        distDate: this.dist.busDate,
        deptName: this.dist.deptName,
        distSummary
      }
      return [dist]
    },
    printDistQR() {
      const params = {
        labelKey: 'dist_qr',
        data: this.getPrintData()
      }
      this.$ajax.post('/sys/printer/printLabel', params).then(res => {
        this.$notify.success('已推送打印配送二维码')
      })
    },
    resetScan() {
      this.scan = ''
      this.$refs.scanDom.focus()
    },
    clearForm() {
      this.dist = {}
      this.distItems = []
      this.pickItems = []
      this.resetScan()
    }
  },
  components: {
    ReceiveItem, FlowButtons
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .edit-field {
    background-color: lightblue;
  }
  .btn-container {
    position: absolute;
    left:0;
    bottom: 0;
    padding:5px;
    width:100%;
    flex-direction:column ;
    display: flex;
    justify-content: space-between;
  }
  .matr-name {
    font-size:12px;
    font-weight: 600;
  }
  .matr-spec {
    font-size:12px;
  }
  .matr-qty {
    width: 40px;
    text-align: center;
    display: inline-block;
  }
  .value-container {
    height: 50px;
    display:flex;
    justify-content:left;
    align-items: center;
  }
  .icon-container {
    height: 50px;
    display:flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .passed {
    color: green;
  }
  .warning {
    color: orangered;
  }
</style>
